package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.Date;

import de.greenrobot.event.EventBus;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.Constant;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.bean.GoodType;
import xhwl.hmo.mall.bean.TZConfirmOrder;
import xhwl.hmo.mall.event.PaymentFinishEvent;
import xhwl.hmo.mall.http.api.BuyApi;
import xhwl.hmo.mall.http.bean.resp.BuyResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.utils.AlarmUtil;
import xhwl.hmo.mall.utils.AndroidBug5497Workaround;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.IdcardValidator;
import xhwl.hmo.mall.utils.NumberJudgeUtils;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.views.AutoSplitTextView;
import xhwl.hmo.mall.views.ChineseEditText;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 购买填写保障人信息界面
 * Created by admin on 2017-10-24.
 */

public class SubmitPersonInfoActivity extends BaseActivity implements View.OnClickListener {
    public static final String EXTRA_SALE_TYPE="saleType";
    public static final String EXTRA_PRICE="price";
    public static final String EXTRA_SALE_PRICE="salePrice";
    public static final String EXTRA_GOODS_NAME="goodsName";
    public static final String EXTRA_GOODS_PIC="goodsPicUrl";
    public static final String EXTRA_GOOD_TYPE="goodType";
    private android.widget.TextView tvProductName;
    private android.widget.TextView tvProductPriceOrigin;
    private android.widget.TextView tvProductPrice;
    private xhwl.hmo.mall.views.ChineseEditText etPersonName;
    private AutoSplitTextView tvDesc1,tvDesc2;
    private android.widget.EditText etPhone;
    private android.widget.EditText etCardNo;
    private android.widget.Button btnConfirm;
    ImageView ivGoods;
    String goodsName,goodPicUrl,saleType,price,salePrice;
    String goodType;
    String personSex="";
    String personAge="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        goodsName=getIntent().getStringExtra(EXTRA_GOODS_NAME);
        goodPicUrl=getIntent().getStringExtra(EXTRA_GOODS_PIC);
        saleType=getIntent().getStringExtra(EXTRA_SALE_TYPE);
        price=getIntent().getStringExtra(EXTRA_PRICE);
        salePrice=getIntent().getStringExtra(EXTRA_SALE_PRICE);
        goodType=getIntent().getStringExtra(EXTRA_GOOD_TYPE);
//
//        goodsName="百倍爱心卡";
//        goodPicUrl="http://101.254.183.186:6688/upload/goods_pic/42644.gif";
//        saleType="1";
//        price="200";
//        salePrice="150";

        setContentView(R.layout.activity_submit_person_info);
        AndroidBug5497Workaround.assistActivity(this);

    }

    @Override
    public void initViews() {
        initTitleViews();
        this.btnConfirm = (Button) findViewById(R.id.btnConfirm);
        this.tvDesc2 = (AutoSplitTextView) findViewById(R.id.tvDesc2);
        this.etCardNo = (EditText) findViewById(R.id.etCardNo);
        this.etPhone = (EditText) findViewById(R.id.etPhone);
        this.tvDesc1 = (AutoSplitTextView) findViewById(R.id.tvDesc1);
        this.etPersonName = (ChineseEditText) findViewById(R.id.etPersonName);
        this.tvProductPrice = (TextView) findViewById(R.id.tvProductPrice);
        this.tvProductPriceOrigin = (TextView) findViewById(R.id.tvProductPriceOrigin);
        this.tvProductName = (TextView) findViewById(R.id.tvProductName);
        this.ivGoods= (ImageView) findViewById(R.id.ivGoods);
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        this.titleTextView.setText("填写保障人信息");
    }

    @Override
    public void initListener() {
        this.btnConfirm.setOnClickListener(this);
        this.etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()==11&&!NumberJudgeUtils.isMobileNO(etPhone.getText().toString())) {
                    ToastUtil.showToast(mContext,"手机号格式错误，请输入正确的手机号");
                }
            }
        });
        this.etCardNo .addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() == 18) {
                    String idNumber = s.toString();
                    String returnMsg = IdcardValidator.validate18Idcard(idNumber);
                    if (StringUtil.isEmpty(returnMsg)) {
                        try {
                            String strYear = idNumber.substring(6, 10);// 年份
                            String strMonth = idNumber.substring(10, 12);// 月份
                            String strDay = idNumber.substring(12, 14);// 月份
//                            date.setText(strYear + "-" + strMonth + "-" + strDay);
                            int Year = Integer.parseInt(strYear);
                            int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
                            personAge = String.valueOf(currentYear - Year);
                            String sexStr = idNumber.substring(15, 17);
                            int sex = Integer.parseInt(sexStr);
                            if (sex % 2 == 0) {
                                personSex = "1";
                            } else {
                                personSex = "0";
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            ToastUtil.showToast(mContext, e.getMessage());
                        }
                    } else {
                        ToastUtil.showToast(mContext, returnMsg);
                    }
                }
                else
                {
                    personSex="";
                    personAge="";
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    protected void processOper() {
        this.tvProductName.setText(goodsName);
        this.tvProductPriceOrigin.setText("￥"+price+"/年");
        this.tvProductPrice.setText("￥"+salePrice+"/年");
        Glide.with(this).load(goodPicUrl).into(this.ivGoods);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.btnConfirm){
            if(vilidInput()){
                if(GoodType.TZ.equals(goodType)){
                    //进入订单确认页
                    Intent intent=new Intent(mContext,ConfirmOrderActivity.class);
                    TZConfirmOrder confirmOrder=new TZConfirmOrder(goodsName,saleType,price,salePrice,
                            goodPicUrl,etPersonName.getText().toString(),etPhone.getText().toString(), etCardNo.getText().toString(),personSex,personAge);
                    intent.putExtra(ConfirmOrderActivity.EXTRA_DATA,confirmOrder);
                    startActivity(intent);
                }else
                {
                    //直接购买
                    buy("");
                }
            }
        }
    }
    private void buy(String addressId){
        String memberMobile= SpUtil.getString(SpUtil.MEMBER_MOBILE,"");
        BuyApi.BuyReq req=new BuyApi.BuyReq(memberMobile,etPersonName.getText().toString(),etPhone.getText().toString()
        ,etCardNo.getText().toString(),personSex,personAge,saleType,salePrice,addressId);
        BuyApi api=new BuyApi(req);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<BuyResp>>() {
            @Override
            public void onNext(HttpResp<BuyResp> resp) {
                if(resp.isOk()){
                    String orderId=resp.data.order_id;
                    //开启定时任务
                    Intent intent = new Intent(IntentConstants.Action.orderRemind);
                    intent.putExtra(IntentConstants.EXTRA_REMIND_ORDER_ID, orderId);
//                    intent.putExtra(IntentConstants.EXTRA_GOODS_TYPE,  goodType);
                    long triggerAtTime = System.currentTimeMillis()  + Constant.REMIND_ORDER_TIME;
                    AlarmUtil.controlAlarm(mContext, triggerAtTime,Integer.parseInt(orderId), intent);

                    AppUtil.startPayment(mContext,orderId,goodsName,salePrice);
                }
                else
                {
                    ToastUtil.showToast(mContext,resp.message);
                }
            }
        });
    }
    private boolean vilidInput() {
        String msg="";
        String personName=this.etPersonName.getText().toString();
        String personMobile=this.etPhone.getText().toString();
        if(StringUtil.isEmpty(personName)){
            msg="请输入保障人姓名";
        }else if(StringUtil.isEmpty(personMobile)){
            msg="请输入保障人手机号";
        }else if(!NumberJudgeUtils.isMobileNO(etPhone.getText().toString())){
            msg="手机号格式错误，请输入正确的手机号";
        }else if(!NumberJudgeUtils.isMobileNO(etPhone.getText().toString())){
            msg="手机号格式错误，请输入正确的手机号";
        }else if(!StringUtil.isEmpty(this.etCardNo.getText().toString())){
            msg=IdcardValidator.validate18Idcard(this.etCardNo.getText().toString());
        }
        if (StringUtil.isEmpty(msg)){
            return true;
        }
        else
        {
            ToastUtil.showToast(mContext,msg);
            return false;
        }
    }
    public void onEvent(PaymentFinishEvent event){
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
